package com.gotop.common.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gotop.common.utils.R;
import com.gotop.common.utils.ResultCode;
import com.gotop.common.utils.WebUtil;
import com.gotop.common.utils.auth.CemUser;
import com.gotop.common.utils.auth.ClientUser;
import com.gotop.common.utils.auth.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @program: cem
 * @description: 拦截器配置
 * @author: superfish
 * @create: 2020-12-21 18:24
 **/
@Slf4j
@Component
public class AuthClientInterceptor extends HandlerInterceptorAdapter {

    private final static String SDK_STR = "/sdk";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("uri: " + request.getRequestURI());
        final String requestURI = request.getRequestURI();
        if (requestURI.startsWith(SDK_STR)) {
            ClientUser client = SecureUtil.getClient();
            if (client != null) {
                return true;
            }
        } else {
            final CemUser user = SecureUtil.getUser();
            if (user != null && StringUtils.equals(user.getClientId(), SecureUtil.getClientIdFromHeader()) && StringUtils.equals(user.getClientId(), user.getClientId())) {
                return true;
            }
        }
        log.warn("客户端认证失败，请求接口：{}，请求IP：{}，请求参数：{}", new Object[]{request.getRequestURI(), WebUtil.getIP(request), request.getParameterMap().toString()});
        final R result = R.fail(ResultCode.UN_AUTHORIZED);
        response.setHeader("Content-type", "application/json");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(Objects.requireNonNull(JSONObject.toJSONString(result)));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return false;
    }
}
